package com.zs.service.rocketmq.producer;

import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;

/**
 * Copyright 2022 ZS Network Co., Ltd. All rights reserved.
 * 本文件仅限于正数网络技术有限公司内部传阅，禁止外泄以及用于其他的商业目的。
 * Created by 张晓珂 on 2022/1/20.
 *
 * @description:
 */
@Component
@Slf4j
@ConditionalOnBean(DefaultMQProducer.class)
public class RocketMqProducer {

    @Autowired
    private DefaultMQProducer defaultMQProducer;

    /**
     * 发送消息
     */
    public void produce(String topic, String tag, String message) {
        if(defaultMQProducer == null){
            throw new RuntimeException("rocketmq未初始化，请检查配置");
        }
        Message sendMsg = new Message(topic, tag, message.getBytes());
        // 默认3秒超时
        try {
            defaultMQProducer.send(sendMsg, new SendCallback() {
                @Override
                public void onSuccess(SendResult sendResult) {

                }

                @Override
                public void onException(Throwable throwable) {
                    log.error("发送mq异常,topic:{},tag:{},msg:{}",topic,tag,message,throwable);
                }
            });
        } catch (Exception e) {
            log.error("生产消息失败：topic：{}, tag:{}, message:{}, e", topic, tag, message, e);
        }
    }

}
